package org.hepeng.workx.validation.validator;

import org.apache.commons.lang3.reflect.FieldUtils;
import org.hepeng.workx.exception.ApplicationRuntimeException;
import org.hepeng.workx.validation.constraints.NonNullFieldOnlyOne;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.Field;
import java.util.Objects;

/**
 * @author he peng
 */
public class NonNullFieldOnlyOneValidator implements ConstraintValidator<NonNullFieldOnlyOne, Object> {

    private NonNullFieldOnlyOne nonNullFieldOnlyOne;

    @Override
    public void initialize(NonNullFieldOnlyOne constraintAnnotation) {
        this.nonNullFieldOnlyOne = constraintAnnotation;
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {

        boolean isValid = true;
        int nonNullFieldCount = 0;
        try {
            for (String fieldName : this.nonNullFieldOnlyOne.fieldNames()) {
                Field field = FieldUtils.getField(value.getClass(), fieldName, true);
                field.setAccessible(true);
                if (Objects.nonNull(field.get(value))) {
                    nonNullFieldCount++;
                }
            }
        } catch (Exception e) {
            throw new ApplicationRuntimeException(e);
        }

        if (nonNullFieldCount > 1) {
            isValid = false;
        }

        return isValid;
    }
}
